package com.sk.other;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapDeepCopy {
    public static void main(String[] args) {
        Map<String, User> map0 = new HashMap<>();
        map0.put("one", new User("张三", "男"));

        Map<String, User> map1 = new HashMap<>();
        map1.putAll(map0);
        User user = map1.get("one");
        user.sex = "女";

        System.out.println(map0.get("one").sex);

        map1.put("two",new User("李四","男"));
        User user1 = map0.get("two");
        //System.out.println(user1.name);


        List<User> list0 = new ArrayList<>();
        list0.add(new User("张三","女"));
        List<User> list1 = new ArrayList<>();
        list1.addAll(list0);
        User user2 = list1.get(0);
        user2.sex = "nan";
        System.out.println(list0.get(0).sex);
    }

    public static Object deepClone(Object obj) {
        try {// 将对象写到流里
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);// 从流里读出来
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            return (oi.readObject());
        } catch (Exception e) {
            return null;
        }
    }

}

class User implements Cloneable {
    String name;
    String sex;

    User(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}